using System;
using System.Reflection;

namespace MyWebPagesStarterKit.Sitemaps.Utilities
{
    internal static class AssemblyUtils
    {
        public static string FormatVersion(Version assemblyVersion)
        {
            if (assemblyVersion.Build == 0)
            {
                return (assemblyVersion.Major + "." + assemblyVersion.Minor);
            }
            return string.Concat(new object[] { assemblyVersion.Major, ".", assemblyVersion.Minor, ".", assemblyVersion.Build });
        }

        public static T GetAttribute<T>(ICustomAttributeProvider attributeProvider) where T: Attribute
        {
            return GetAttribute<T>(attributeProvider, false, true);
        }

        public static T GetAttribute<T>(ICustomAttributeProvider attributeProvider, bool errorOnMultiple) where T: Attribute
        {
            return GetAttribute<T>(attributeProvider, errorOnMultiple, true);
        }

        public static T GetAttribute<T>(ICustomAttributeProvider attributeProvider, bool errorOnMultiple, bool inherit) where T: Attribute
        {
            T[] attributes = GetAttributes<T>(attributeProvider, inherit);
            if (CollectionUtils.IsNullOrEmpty<T>(attributes))
            {
                return default(T);
            }
            if (attributes.Length != 1)
            {
                throw new AmbiguousMatchException(string.Format("Multiple attributes of type '{0}' found.", typeof(T).Name));
            }
            return attributes[0];
        }

        public static T[] GetAttributes<T>(ICustomAttributeProvider attributeProvider, bool inherit) where T: Attribute
        {
            return (T[]) attributeProvider.GetCustomAttributes(typeof(T), inherit);
        }

        public static string GetCompleteProductName(Assembly assembly)
        {
            return (GetProductName(assembly) + " " + FormatVersion(assembly.GetName().Version));
        }

        public static string GetCopyright(Assembly assembly)
        {
            return GetAttribute<AssemblyCopyrightAttribute>(assembly).Copyright;
        }

        public static string GetProductName(Assembly assembly)
        {
            return "MywebpagesStarterKit"; //GetAttribute<AssemblyProductAttribute>(assembly).Product;
        }
    }
}
